#!/bin/bash
#Author: zhangbolin10@crc.com.hk
#Version: 0.1.0
#Describe: Nginx Listen Port Check
#Define Nginx config file
NGINX_CONF="/etc/nginx/nginx.conf"
#get nginx Listen port

function getListenPort() {
    #get
    CONF=$(cat ${1})
    echo "${CONF}" | grep -E "^[ \t]*listen *.*" | grep -E -o "[0-9]+.[0-9]+.[0-9]+.[0-9]+:[0-9]+"
    #get include file
    CONF=$(echo "${CONF}" | grep -E "^[ \t]*include *.*" | sed 's\^[ \t]*include[ \t]*\\g' | sed 's\;\\g')
    #recursive get include file ListenPort
    for SUB_CONF in ${CONF}; do
        if [ -f ${SUB_CONF} ]; then
            getListenPort ${SUB_CONF}
        fi
    done
}

ListenPort=$(getListenPort ${NGINX_CONF})

function curlListenPort() {
    curl -sIL -w "$1 %{http_code} \n" -o /dev/null $1
}

function checkListenPort() {
    printf "ListenPort HTTP_STATUS_CODE \n"
    for URL in ${ListenPort}; do
        curlListenPort ${URL} &
    done
    wait
}

checkListenPort
